/*
 * Copyright 2011 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.lansir.af.ui;

import java.util.ArrayList;

import org.lansir.af.R;
import org.lansir.af.gtalk.ui.AddContact;
import org.lansir.af.gtalk.ui.ChangeStatus;
import org.lansir.af.gtalk.ui.Settings;
import org.lansir.af.gtalk.utils.GtalkBroadcastReceiver;
import org.lansir.af.ui.phone.LoginActivity;
import org.lansir.af.view.WidgetQuickActionDialog;
import org.lansir.af.view.WidgetQuickActionDialogItem;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TabHost;
import android.widget.TabWidget;
import android.widget.TextView;

/**
 * An activity that shows the user's starred sessions and sandbox companies. This activity can be
 * either single or multi-pane, depending on the device configuration. We want the multi-pane
 * support that {@link BaseMultiPaneActivity} offers, so we inherit from it instead of
 * {@link BaseSinglePaneActivity}.
 */
public class ContactListActivity extends BaseActivity {
	private static final Intent SERVICE_INTENT = new Intent("org.lansir.af.gtalk.GtalkService");
    public static final String TAG_CONTASTLIST = "ContactList";
    public static final String TAG_CHATLIST = "ChatList";

    private TabHost mTabHost;
    private TabWidget mTabWidget;
    private ViewPager mViewPager;
    private TabsAdapter mTabsAdapter;
    private WidgetQuickActionDialog mQuickActionDialog;

    private final GtalkBroadcastReceiver mReceiver = new GtalkBroadcastReceiver();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_tabs_pager);
        getActivityHelper().setupActionBar(getTitle(), 0);

        mTabHost = (TabHost) findViewById(android.R.id.tabhost);
        mTabWidget = (TabWidget) findViewById(android.R.id.tabs);
        mTabHost.setup();
        mViewPager = (ViewPager)findViewById(R.id.pager);
        mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);
        mTabsAdapter.addTab(mTabHost.newTabSpec("ContactList").setIndicator(buildIndicator(R.string.tab_contactlist)),
                ContactListFragment.class, intentToFragmentArguments(getIntent()));
        mTabsAdapter.addTab(mTabHost.newTabSpec("ChatList").setIndicator(buildIndicator(R.string.tab_chatlist)),
                ChatListFragment.class, intentToFragmentArguments(getIntent()));
        
        registerReceiver(mReceiver, new IntentFilter(GtalkBroadcastReceiver.Gtalk_CONNECTION_CLOSED));
        if (savedInstanceState != null) {
            mTabHost.setCurrentTabByTag(savedInstanceState.getString("tab"));
        }

//        setupContactListTab();
//        setupChatListTab();
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        getActivityHelper().setupSubActivity();
       
    }
    
    
    
    @Override
	public boolean onCreateOptionsMenu(Menu menu) {
    	this.getMenuInflater().inflate(R.menu.contact_list, menu);
    	mQuickActionDialog = new WidgetQuickActionDialog(this);
    	mQuickActionDialog.addMenuItems(new WidgetQuickActionDialogItem(R.drawable.ic_title_add, R.string.contact_list_menu_add_contact, new OnClickListener(){
			@Override
			public void onClick(View v) {
				mQuickActionDialog.dismiss();
				startActivity(new Intent(ContactListActivity.this, AddContact.class));				
				
			}	
		}));
    	mQuickActionDialog.addMenuItems(new WidgetQuickActionDialogItem(R.drawable.ic_title_status, R.string.contact_list_menu_status, new OnClickListener(){
			@Override
			public void onClick(View v) {
				mQuickActionDialog.dismiss();
				startActivity(new Intent(ContactListActivity.this, ChangeStatus.class));
				
			}	
		}));
    	mQuickActionDialog.addMenuItems(new WidgetQuickActionDialogItem(R.drawable.ic_title_changeuser, R.string.contact_list_menu_changeuser, new OnClickListener(){
			@Override
			public void onClick(View v) {
				mQuickActionDialog.dismiss();
				stopService(SERVICE_INTENT);
				Intent intent = new Intent(ContactListActivity.this, LoginActivity.class);
				Bundle bundle = new Bundle();
				bundle.putBoolean("ChangeUser", true);
				intent.putExtras(bundle);
				startActivity(intent);
				finish();				
			}	
		}));
    	mQuickActionDialog.addMenuItems(new WidgetQuickActionDialogItem(R.drawable.ic_title_settings, R.string.contact_list_menu_settings, new OnClickListener(){
			@Override
			public void onClick(View v) {
				mQuickActionDialog.dismiss();
				startActivity(new Intent(ContactListActivity.this, Settings.class));				
			}	
		}));
    	mQuickActionDialog.addMenuItems(new WidgetQuickActionDialogItem(R.drawable.ic_title_close_clear_cancel, R.string.contact_list_menu_disconnect, new OnClickListener(){
			@Override
			public void onClick(View v) {
				mQuickActionDialog.dismiss();
				stopService(SERVICE_INTENT);
				finish();
			}	
		}));
//    	inflater.inflate(R.menu.contact_list, menu);
		return super.onCreateOptionsMenu(menu);
	}

//	@Override
//	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
//		inflater.inflate(R.menu.contact_list, menu);
//		super.onCreateOptionsMenu(menu, inflater);
//	}



	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.contact_list_menu_more:
			mQuickActionDialog.showAsDropDown(findViewById(R.id.contact_list_menu_more));
			return true;
		
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(mReceiver);
	}
   
    /**
     * Build a {@link View} to be used as a tab indicator, setting the requested string resource as
     * its label.
     */
    private View buildIndicator(int textRes) {
        final TextView indicator = (TextView) getLayoutInflater().inflate(R.layout.tab_indicator,
                mTabWidget, false);
        indicator.setText(textRes);
        return indicator;
    }
    
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("tab", mTabHost.getCurrentTabTag());
    }

    /**
     * This is a helper class that implements the management of tabs and all
     * details of connecting a ViewPager with associated TabHost.  It relies on a
     * trick.  Normally a tab host has a simple API for supplying a View or
     * Intent that each tab will show.  This is not sufficient for switching
     * between pages.  So instead we make the content part of the tab host
     * 0dp high (it is not shown) and the TabsAdapter supplies its own dummy
     * view to show as the tab content.  It listens to changes in tabs, and takes
     * care of switch to the correct paged in the ViewPager whenever the selected
     * tab changes.
     */
    public static class TabsAdapter extends FragmentPagerAdapter
            implements TabHost.OnTabChangeListener, ViewPager.OnPageChangeListener {
        private final Context mContext;
        private final TabHost mTabHost;
        private final ViewPager mViewPager;
        private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();

        static final class TabInfo {
            private final String tag;
            private final Class<?> clss;
            private final Bundle args;

            TabInfo(String _tag, Class<?> _class, Bundle _args) {
                tag = _tag;
                clss = _class;
                args = _args;
            }
        }

        static class DummyTabFactory implements TabHost.TabContentFactory {
            private final Context mContext;

            public DummyTabFactory(Context context) {
                mContext = context;
            }

            @Override
            public View createTabContent(String tag) {
                View v = new View(mContext);
                v.setMinimumWidth(0);
                v.setMinimumHeight(0);
                return v;
            }
        }

        public TabsAdapter(FragmentActivity activity, TabHost tabHost, ViewPager pager) {
            super(activity.getSupportFragmentManager());
            mContext = activity;
            mTabHost = tabHost;
            mViewPager = pager;
            mTabHost.setOnTabChangedListener(this);
            mViewPager.setAdapter(this);
            mViewPager.setOnPageChangeListener(this);
        }

        public void addTab(TabHost.TabSpec tabSpec, Class<?> clss, Bundle args) {
            tabSpec.setContent(new DummyTabFactory(mContext));
            String tag = tabSpec.getTag();

            TabInfo info = new TabInfo(tag, clss, args);
            mTabs.add(info);
            mTabHost.addTab(tabSpec);
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return mTabs.size();
        }

        @Override
        public Fragment getItem(int position) {
            TabInfo info = mTabs.get(position);
            return Fragment.instantiate(mContext, info.clss.getName(), info.args);
        }

        @Override
        public void onTabChanged(String tabId) {
            int position = mTabHost.getCurrentTab();
            mViewPager.setCurrentItem(position);
        }

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {
            mTabHost.setCurrentTab(position);
        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }
    }
    
}
